package com.InetAddressDemo.multicast;


import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;

/**接收端
 *
 * @Author weijingchen
 * @Date 2025/6/23 22:49
 * @Version 1.0.0
 */
public class Test03 {
    public static void main(String[] args) {
        try {
            //创建组播对象
            MulticastSocket ms = new MulticastSocket(8888);
            //加入组播
            InetAddress ia = InetAddress.getByName("224.0.0.2");
            ms.joinGroup(ia);
            byte[] bytes = new byte[1024];
            DatagramPacket dp = new DatagramPacket(bytes, bytes.length);
            //接收数据
            ms.receive(dp);

            //解析数据
            byte[] data = dp.getData();
            int length = dp.getLength();
            String hostName = dp.getAddress().getHostName();
            String address = dp.getAddress().getHostAddress();
            System.out.println("ip：" +address + "  name：" + hostName+"  data：" + new String(data,0,length));
            //释放资源
            ms.close();

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
